package spring.cloud.tasks.executor.listener.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class TaskCronUpdateListener extends TreeCacheListener {

    private final ConfigurationListenerHolder configurationListener;

    public TaskCronUpdateListener(ConfigurationListenerHolder configurationListener) {
        this.configurationListener = configurationListener;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (configurationListener.isShutdown) {
            return;
        }
        if (ConfigurationNode.isCronPath(configurationListener.taskId, path) && TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) {
            LogUtils.info(log, configurationListener.taskId, "{} 's cron update", configurationListener.taskId);
            String cronExpressionFromZooKeeper = configurationListener.taskConfiguration.getCronExpressionFromZooKeeper(); // will update local cron cache
            if (!configurationListener.taskExecutor.getPreviousJobConfiguration().getCronExpression().equals(cronExpressionFromZooKeeper)) {
                configurationListener.taskExecutor.getPreviousJobConfiguration().setCronExpression(cronExpressionFromZooKeeper);
                configurationListener.taskExecutor.reInitializeTrigger();
                configurationListener.executeService.updateNextFireTime(configurationListener.taskExecuteContextService.getTaskItemIndexList());
            }
        }
    }
}
